package com.bytedance.ttnet.utils;

import android.util.Pair;

import com.bytedance.frameworks.baselib.network.http.c.SsHttpExecutor;
import com.bytedance.frameworks.baselib.network.http.exception.HttpResponseException;
import com.bytedance.frameworks.baselib.network.http.parser.MimeType;
import com.bytedance.frameworks.baselib.network.http.util.TaskInfo;
import com.bytedance.retrofit2.Call;
import com.bytedance.retrofit2.Converter;
import com.bytedance.retrofit2.HttpUrl;
import com.bytedance.retrofit2.ResponseWrapper;
import com.bytedance.retrofit2.Retrofit;
import com.bytedance.retrofit2.Utils;
import com.bytedance.retrofit2.client.Client;
import com.bytedance.retrofit2.client.Header;
import com.bytedance.retrofit2.mime.TypedInput;
import com.bytedance.ttnet.INetworkApi;
import com.bytedance.ttnet.b.RequestParams;
import com.bytedance.ttnet.c.SsOkHttpClient;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

import inline.NetworkDemo;

public final class RetrofitUtils {
    public enum CompressType {
        NONE(0),
        GZIP(1),
        DEFLATER(2);

        final int nativeInt;

        CompressType(int i) {
            this.nativeInt = i;
        }
    }


    private static Map<String, Retrofit> a = new HashMap();
    private static Map<String, Retrofit> b = new HashMap();

    public static synchronized <S> S createService(String website, Class<S> service) {
        Retrofit retrofit = RetrofitUtils.createRetrofit(website);
        return RetrofitUtils.createService(retrofit, service);
    }

    public static Pair a(String mime) {
        if (mime != null) {
            try {
                MimeType mimeType = new MimeType(mime);
                String baseType = mimeType.getBaseType();
                String charset = mimeType.getParameter("charset");
                return new Pair(baseType, charset);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
        return null;
    }

    public static synchronized Retrofit createRetrofit(String url, SsOkHttpClient ssOkHttpClient, Converter.Factory convertFactory) {
        return RetrofitUtils.createRetrofit(url, ssOkHttpClient, convertFactory, new d());
    }

    private static Retrofit createRetrofit(String url, SsOkHttpClient ssOkHttpClient, Converter.Factory convertFactory, Client.Provider clientProvider) {
        synchronized (RetrofitUtils.class) {
            if (ssOkHttpClient == null) {
                ssOkHttpClient = new SsOkHttpClient();
            }
            if (convertFactory == null) {
                convertFactory = com.bytedance.frameworks.baselib.network.http.c.a.a.a.a();
            }

            Retrofit.Builder builder = new Retrofit.Builder();
            if (url != null && url.trim().length() != 0) {
                builder.baseUrl = new HttpUrl(url);
                builder.clientProvider = Utils.checkNotNull(Utils.checkNotNull(clientProvider, "provider == null"), "provider == null");
                builder.requestInterceptor = Utils.checkNotNull(ssOkHttpClient, "requestInterceptor == null");
                builder.responseInterceptor = Utils.checkNotNull(ssOkHttpClient, "responseInterceptor == null");
                builder.httpExecutor = Utils.checkNotNull(new SsHttpExecutor(), "httpExecutor == null");
                builder.converterFactories.add(Utils.checkNotNull(convertFactory, "factory == null"));
                if (builder.baseUrl == null) {
                    throw new IllegalStateException("Endpoint may not be null.");
                } else if (builder.clientProvider == null) {
                    throw new IllegalStateException("ClientProvider may not be null.");
                } else if (builder.httpExecutor == null) {
                    throw new IllegalStateException("HttpExecutor may not be null.");
                } else {
                    Executor callbackExecutor = builder.platform.defaultCallbackExecutor();
                    ArrayList adapterFactoryList = new ArrayList(builder.adapterFactories);
                    adapterFactoryList.add(builder.platform.defaultCallAdapterFactory(callbackExecutor));
                    Retrofit retrofit = new Retrofit(
                            builder.baseUrl,
                            builder.clientProvider,
                            builder.requestInterceptor,
                            builder.responseInterceptor,
                            new ArrayList(builder.converterFactories),
                            adapterFactoryList,
                            builder.httpExecutor);
                    return retrofit;
                }
            } else {
                throw new NullPointerException("Endpoint may not be blank.");
            }
        }
    }

    public static synchronized <S> S createService(Retrofit retrofit, Class<S> clazz) {
        S service;
        if (retrofit != null) {
            service = retrofit.create(clazz);
        } else {
            service = null;
        }
        return service;
    }

    private static void extractRemoteIp(String[] remoteIp, List<Header> headerList, RequestParams requestContext) {
        if (remoteIp != null && remoteIp.length >= 0) {
            if (headerList != null && headerList.size() > 0) {
                Iterator<Header> iterator = headerList.iterator();
                while (iterator.hasNext()) {
                    Header header = iterator.next();
                    if ("x-snssdk.remoteaddr".equalsIgnoreCase(header.name)) {
                        remoteIp[0] = header.value;
                        break;
                    }
                }
            }
            if (android.support.design.a.isTextEmpty(remoteIp[0])) {
                remoteIp[0] = requestContext.remoteIp;
            }
        }
    }

    @Deprecated
    public static boolean downloadFile(int maxLength,
                                       String url,
                                       String arg22,
                                       String arg23,
                                       String arg24,
                                       com.bytedance.frameworks.baselib.network.http.util.d arg25,
                                       String arg26,
                                       TaskInfo taskInfo,
                                       List<Header> headers,
                                       String[] remoteIp,
                                       int[] contentLength) throws Exception {
        if (android.support.design.a.isTextEmpty(url)) {
            return false;
        } else {
            LinkedHashMap<String,String> queryMap = new LinkedHashMap();
            Pair<String, String> pair = NetworkDemo.parseUrl(url, queryMap);
            String host = pair.first;
            String path = pair.second;
            INetworkApi networkApi = RetrofitUtils.createService(host, INetworkApi.class);
            RequestParams requestParams = new RequestParams();
            if (networkApi != null) {
                Call<TypedInput> call = networkApi.downloadFile(false, maxLength, path, queryMap, headers, requestParams);
                if (taskInfo != null && taskInfo.a) {
                    return false;
                }

                if (!android.support.design.a.isNetworkAvailable(com.bytedance.ttnet.cc.a().getContext())) {
                    return false;
                }

                InputStream inputStream = null;
                try {
                    ResponseWrapper<TypedInput> responseWrapper = call.execute();
                    if (responseWrapper != null) {
                        TypedInput typedInput = responseWrapper.body;
                        if (typedInput != null) {
                            inputStream = typedInput.in();
                        }
                        List<Header> headerList = responseWrapper.rawResponse.headers;
                        RetrofitUtils.extractRemoteIp(remoteIp, headerList, requestParams);
                        int responseCode = responseWrapper.rawResponse.status;
                        if (responseCode == 200 && typedInput != null) {
                            long length = typedInput.length();
                            if (contentLength != null && contentLength.length > 0) {
                                if (length <= Integer.MAX_VALUE) {
                                    contentLength[0] = (int) length;
                                } else {
                                    contentLength[0] = 0;
                                }
                            }
                            boolean v2 = android.support.design.a.readInputStream(
                                    inputStream,
                                    typedInput.length(),
                                    new com.bytedance.ttnet.utils.b(url, call),
                                    maxLength,
                                    arg22,
                                    arg23,
                                    arg24,
                                    arg25,
                                    arg26,
                                    taskInfo);
                            android.support.design.a.closeQuietly(inputStream, null);
                            return v2;
                        }
                        if (responseCode == 200 && typedInput == null) {
                            try {
                                throw new IllegalArgumentException("HTTP TypedInput may not be null");
                            } catch (Exception exception) {
                                try {
                                    RetrofitUtils.extractRemoteIp(remoteIp, headerList, requestParams);
                                    throw exception;
                                } catch (Throwable throwable) {
                                    android.support.design.a.closeQuietly(inputStream, null);
                                    throw throwable;
                                }
                            }
                        }
                        throw new HttpResponseException(responseCode, "get url = " + url + " exception");
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                android.support.design.a.closeQuietly(null, null);
                return false;
            } else {
                return false;
            }
        }
    }

    private static synchronized Retrofit createRetrofit(String url) {
        if (android.support.design.a.isTextEmpty(url)) {
            return null;
        }

        Retrofit retrofit = RetrofitUtils.a.get(url);
        if (retrofit == null) {
            retrofit = RetrofitUtils.createRetrofit2(url);
            RetrofitUtils.a.put(url, retrofit);
        }
        return retrofit;
    }

    public static synchronized <T> T createService2(String website, Class<T> service) {
        return RetrofitUtils.createService(RetrofitUtils.d(website), service);
    }

    private static Retrofit createRetrofit2(String url) {
        return RetrofitUtils.createRetrofit(url, null, null, new c());
    }

    private static synchronized Retrofit d(String url) {
        Retrofit retrofit = null;
        if (!android.support.design.a.isTextEmpty(url)) {
            retrofit = RetrofitUtils.b.get(url);
            if (retrofit == null) {
                retrofit = RetrofitUtils.createRetrofit(url, null, null);
                RetrofitUtils.b.put(url, retrofit);
            }
        }
        return retrofit;
    }
}

